/**
 * GET users listing.
 */
var redis = require("../Redis/redis.js");
exports.confirmDlg = function(req, res) {
	"use strict";
	var query = req.query;

	res.render("confirmDlg", query);
};

exports.pingServer = function(req, res) {
	"use strict";
	res.send("ok");
};

exports.restart = function(req, res) {
	"use strict";
	res.writeHead(200, {
		"Content-Type" : "text/plain"
	});
	res.end("ok", function() {
		process.exit(0);
	});
};

exports._cleanupDatabase = function(req, res) {
	"use strict";
	var context = {};
	redis.setClient(context);

	var redisc = context.redis;
	redisc.flushdb(function(err) {
		if (err) {
			res.send("" + err);
		} else {
			res.send("ok");
		}
	});
};

exports._updateServer = function(req, res) {
	"use strict";
	console.error("uploadLanServer ..");
	var fs = require("fs");
	var exec = require("child_process").exec;
	var tmpPath = "" + req.files.lanServer.path;
	var fileName = "" + req.files.lanServer.name;
	var targetPath = "public/update/" + fileName;
	if (fileName === "" || (tmpPath === "")) {
		res.send("upload file is not exist");
	}

	function recoverFile(callback) {
		var cb = function(err) {
			if (err) {
				callback(err);
				console.error("exec tar error: " + JSON.stringify(err));
			} else {
				callback(null);
			}
		};
		
		fs.rename(tmpPath, targetPath,
				function(err) {
					if (err) {
						callback(err);
						console.error("rename error: " + err);
					} else {
						if (fs.existsSync(tmpPath)) {
							fs.unlink(tmpPath);
						}
						exec("tar -xvf " + targetPath + " -C ../../",
								cb);
					}
				});
	}

	if (fs.existsSync(targetPath)) {
		fs.unlink(targetPath, function(err) {
			if (err) {
				res.send("can't to remvoe old file: " + err);
			} else {
				recoverFile(function(err) {
					if (err) {
						res.send(err);
					} else {
						res.send("ok");
					}
				});
			}
		});
	} else {
		recoverFile(function(err) {
			if (err) {
				res.send(err);
			} else {
				res.send("ok");
			}
		});
	}
};
